package com.yuehuanghun.admin.core.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.yuehuanghun.admin.core.config.UserConstants;
import com.yuehuanghun.admin.core.config.constant.CacheKeys;
import com.yuehuanghun.admin.core.domain.SysConfig;
import com.yuehuanghun.admin.core.mapper.SysConfigMapper;
import com.yuehuanghun.admin.core.service.ISysConfigService;
import com.yuehuanghun.framework.annotation.DataSource;
import com.yuehuanghun.framework.annotation.DataSource.DataSourceType;
import com.yuehuanghun.framework.exception.ValidateException;
import com.yuehuanghun.framework.util.StringUtils;
import com.yuehuanghun.mybatis.milu.ext.BaseServiceImpl;

/**
 * 参数配置 服务层实现
 * 
 * @author yadmin
 */
@Service
public class SysConfigServiceImpl extends BaseServiceImpl<SysConfig, Long, SysConfigMapper> implements ISysConfigService {
	@Autowired
	private SysConfigMapper configMapper;

	@Autowired
	private CacheManager cacheManager;

	/**
	 * 项目启动时，初始化参数到缓存，预热
	 */
	@PostConstruct
	public void init() {
		List<SysConfig> configsList = configMapper.findAll();
		for (SysConfig config : configsList) {
			cacheManager.getCache(CacheKeys.SYS_CONFIG).put(config.getConfigKey(), config.getConfigValue());
		}
	}

	/**
	 * 查询参数配置信息
	 * 
	 * @param configId 参数配置ID
	 * @return 参数配置信息
	 */
	@Override
	@DataSource(DataSourceType.MASTER)
	public SysConfig getConfigById(Long configId) {
		return configMapper.findById(configId).orElse(null);
	}

	/**
	 * 根据键名查询参数配置信息
	 * 
	 * @param configKey 参数key
	 * @return 参数键值
	 */
	@Override
	@Cacheable(cacheNames = CacheKeys.SYS_CONFIG, key = "#p0")
	public String getConfigByKey(String configKey) {
		Optional<SysConfig> configOpt = configMapper.findByConfigKey(configKey);
		if(configOpt.isPresent()) {
			return configOpt.get().getConfigValue();
		}
		return StringUtils.EMPTY;
	}

	/**
	 * 新增参数配置
	 * 
	 * @param config 参数配置信息
	 * @return 结果
	 */
	@Override
	public int insertConfig(SysConfig config) {
		int row = configMapper.insert(config);
		if (row > 0) {
			cacheManager.getCache(CacheKeys.SYS_CONFIG).put(config.getConfigKey(), config.getConfigValue());
		}
		return row;
	}

	/**
	 * 修改参数配置
	 * 
	 * @param config 参数配置信息
	 * @return 结果
	 */
	@Override
	public int updateConfig(SysConfig config) {
		int row = configMapper.updateById(config);
		if (row > 0) {
			cacheManager.getCache(CacheKeys.SYS_CONFIG).put(config.getConfigKey(), config.getConfigValue());
		}
		return row;
	}

	/**
	 * 批量删除参数信息
	 * 
	 * @param configIds 需要删除的参数ID
	 * @return 结果
	 */
	@Override
	public int deleteConfigByIds(Long[] configIds) {
		List<String> configKeys = new ArrayList<>();
		for (Long configId : configIds) {
			SysConfig config = getConfigById(configId);
			if (StringUtils.equals(UserConstants.YES, config.getConfigType())) {
				throw new ValidateException(String.format("内置参数【%1$s】不能删除 ", config.getConfigKey()));
			}
			configKeys.add(config.getConfigKey());
		}
		int count = configMapper.deleteByIds(Arrays.asList(configIds));
		if (count > 0) {
			Cache cache = cacheManager.getCache(CacheKeys.SYS_CONFIG);
			configKeys.forEach(key -> {
				cache.evict(key);
			});
		}
		return count;
	}

	/**
	 * 清空缓存数据
	 */
	@Override
	public void clearCache() {
		cacheManager.getCache(CacheKeys.SYS_CONFIG).clear();
	}

	/**
	 * 校验参数键名是否唯一
	 * 
	 * @param config 参数配置信息
	 * @return 结果
	 */
	@Override
	public String checkConfigKeyUnique(SysConfig config) {
		Long configId = StringUtils.isNull(config.getConfigId()) ? -1L : config.getConfigId();
		SysConfig info = configMapper.findByConfigKey(config.getConfigKey()).orElse(null);
		if (StringUtils.isNotNull(info) && info.getConfigId().longValue() != configId.longValue()) {
			return UserConstants.NOT_UNIQUE;
		}
		return UserConstants.UNIQUE;
	}
}
